package org.csu.pet_store_2.Controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.request.AlipayTradePagePayRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alipay.api.AlipayClient;

import com.alipay.api.DefaultAlipayClient;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
public class PayController {

        //appid
        private final String APP_ID = "2021000122685985";
        //应用私钥
        private final String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCkxMqjR9Q1ER4EQ/sHa0EbccWzv0Bkwvwh6Y49+Av2Vjm+VvIXsJHJHugwVwbUQ19Wx5sFFyxkvesqDJHL/+1KDXh/TuNu9eMxNxciP+yBiC9X6KI94Ly248JN9f/g7S5PW+vABI3KXmH7OvepSBAVGmZFiRWdg5UPx1sCZwP/C1lAZ1PcuVPDwr6IA5RDB/iQicDzuxmzCynNhGq8r9GRLrxkz4ch5KRSSLVxxPeNbFu0ExJmS5wJ9hJFByH1kvW7J2sxcnQeN/KT21XOdMCa3UrO/uRDYLfkLjkKLp3BomPvDJtL4AFFsxMOt+SgkTv9iiAhAWm/sNfYOwDhrKWTAgMBAAECggEACxMjH6hzTgHRh63eEJiX7rVN+Y/wTxWABvOA2Q90FmGjTfTgHtGCawdFygH/doL0xIt0EvqExFyzksb3gcO4+lI/eCcgSFQEqkkup+GuDuLNc9YyGYCijpRuefj/8uleRH1EMkrcEO8ZHN7QyLMMSa7VkvTs3AJ9IWtf5aBw91J7BNOCj33ccpXQGu/keyNt8FseBa1hl1eetCMtKDKaRYK5dt1b4ZTeMdXNf1dathYCwHwFMCBr8Kx/OpDKdMjfCe72d/vcc2tht0g08mVyuCH5TuCL9AX3XKmvB+GqOV5dXfHmvD805h4l5fhPqfoBRegBj7YPsVTo5PAzpPxqgQKBgQDveAHgxqjBO1yDFKD1aX/UKD1+gddDP1LZCsUN0EbTPKtrvGvzaeNqjYBvAzv1OeAOeigGGnrCtuYTa6YfaNcdQzC/C94r3QNm48hYUdYOd55FD9JzKoHVyue8Yl0UpO8BppbXNPFIVe1u5zV0hEHgzDF+B30/t7Bl94758Ou+QQKBgQCwJKdFspqotQRiHLwYMZUY+JiaCYx5XdsuqS78fNeAnn6b8QtBfQgniZ7gmsUZBidsDpO4E+5eK+zXU6dFSpQ4i5tKg/CpO89qlNKGx4IYnsKSKcQxIvzKWdbdROxSIfR9LDM98yL1w9VyogFiUgc4VBVO1hDWyWBDvhZnOjVW0wKBgQDQhgO8o8DXYsWQLypqCVASgmfp/U5hdIbEEKi++ppx3ua2jgDCmXY6lrU79ekEBT2h3aV0iyJS48k9KAQkXbrT9GpCMidosq//rGIM5lYriuX65WgweNdOP73DQTQkgerN2S6If8WLY6e5ZwQZTgG/qo9+Wy8piN7GK+gIpU3jAQKBgEc3Oo4abR9iuJf2aDIb8d07vW8iBzKWuOR/sKiSzQqKikQAS/25UI+zu5Gx4ZiBfXTZ2+2j2U8n0UUp5EpGofDOuQWCnM2/idfcvdWSWk4b+izgSBtZuv0RH6csk6ONaO0m7rzQTcUx3V3QlGCtK5Ahps/OCtbcalhZRXOM/D3TAoGBAN0R2ryemZSHXgSxevp271zSgDRD6kd5X2WpyPmJM/F81vSq1zEaEmqeEd1mP1V8URQ7EwBFMM0IsH+huwwxqOucymbr4KuSjpUoLHpFi22d0wwwLuaMYPvklFU6o5JDMsQiGQAIy9X+D/O2OXsVzNnL7V/Yb7N3HFpGfn05vaeD";
        private final String CHARSET = "UTF-8";
        // 支付宝公钥
        private final String ALIPAY_PUBLIC_KEY =" MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApMTKo0fUNREeBEP7B2tBG3HFs79AZML8IemOPfgL9lY5vlbyF7CRyR7oMFcG1ENfVsebBRcsZL3rKgyRy//tSg14f07jbvXjMTcXIj/sgYgvV+iiPeC8tuPCTfX/4O0uT1vrwASNyl5h+zr3qUgQFRpmRYkVnYOVD8dbAmcD/wtZQGdT3LlTw8K+iAOUQwf4kInA87sZswspzYRqvK/RkS68ZM+HIeSkUki1ccT3jWxbtBMSZkucCfYSRQch9ZL1uydrMXJ0Hjfyk9tVznTAmt1Kzv7kQ2C35C45Ci6dwaJj7wybS+ABRbMTDrfkoJE7/YogIQFpv7DX2DsA4aylkwIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
        private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
        private final String FORMAT = "JSON";
        //签名方式
        private final String SIGN_TYPE = "RSA2";
        //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
        private final String NOTIFY_URL = "http://127.0.0.1/notifyUrl";
        //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
        private final String RETURN_URL = "http://localhost:8081/index";
    //必须加ResponseBody注解，否则spring会寻找thymeleaf页面

    @PostMapping("/pay/alipay")
    public String alipay(HttpSession session, Model model,
                         @RequestParam("dona_money") int dona_money,
                         @RequestParam("dona_id") int dona_id) throws AlipayApiException {
        //把dona_id项目id 放在session中
        session.setAttribute("dona_id",dona_id);

        //生成订单号（支付宝的要求？）
        String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String user = UUID.randomUUID().toString().replace("-","").toUpperCase();

        String OrderNum = time+user;

        //调用封装好的方法（给支付宝接口发送请求）
        return sendRequestToAlipay(OrderNum,dona_money,"ghjk");
    }
    /*
参数1：订单号
参数2：订单金额
参数3：订单名称
 */
    //支付宝官方提供的接口
    private String sendRequestToAlipay(String outTradeNo,int totalAmount,String subject) throws AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL,APP_ID,APP_PRIVATE_KEY,FORMAT,CHARSET,ALIPAY_PUBLIC_KEY,SIGN_TYPE);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(RETURN_URL);
        alipayRequest.setNotifyUrl(NOTIFY_URL);

        //商品描述（可空）
        String body="";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\","
                + "\"total_amount\":\"" + totalAmount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        return result;
    }

}


